<template>
  <div class="app-container">
    <el-card class="box-card" shadow="never">
      <template #header>
        <div class="card-header">
          <h3>药品管理</h3>
          <div class="right-button">
            <el-button type="primary" @click="handleAdd" v-permission="'drug:add'">
              新增药品
            </el-button>
          </div>
        </div>
      </template>

      <!-- 搜索区域 -->
      <el-form :model="queryParams" ref="queryForm" :inline="true">
        <el-form-item label="药品名称">
          <el-input
            v-model="queryParams.name"
            placeholder="请输入药品名称"
            clearable
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item label="药品编码">
          <el-input
            v-model="queryParams.drugCode"
            placeholder="请输入药品编码"
            clearable
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item label="药品分类">
          <el-select v-model="queryParams.category" placeholder="请选择分类" clearable>
            <el-option label="西药" value="西药" />
            <el-option label="中药" value="中药" />
            <el-option label="中成药" value="中成药" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery">查询</el-button>
          <el-button @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 数据表格 -->
      <el-table
        v-loading="loading"
        :data="drugList"
        style="width: 100%"
        border
      >
        <el-table-column prop="drugCode" label="药品编码" min-width="120" />
        <el-table-column prop="name" label="药品名称" min-width="150">
          <template #default="scope">
            <el-button type="text" @click="handleDetail(scope.row)">
              {{ scope.row.name }}
            </el-button>
          </template>
        </el-table-column>
        <el-table-column prop="genericName" label="通用名" min-width="150" />
        <el-table-column prop="category" label="分类" width="100" />
        <el-table-column prop="specification" label="规格" min-width="150" />
        <el-table-column prop="manufacturer" label="生产厂家" min-width="200" show-overflow-tooltip />
        <el-table-column prop="price" label="售价" width="100">
          <template #default="scope">
            ¥{{ scope.row.price }}
          </template>
        </el-table-column>
        <el-table-column label="库存" width="100">
          <template #default="scope">
            <el-tag 
              :type="getInventoryTagType(scope.row.id)"
              @click="showInventoryDetail(scope.row)"
            >
              {{ getTotalInventory(scope.row.id) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-tag :type="scope.row.status === '启用' ? 'success' : 'danger'">
              {{ scope.row.status }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="scope">
            <el-button-group>
              <el-button 
                type="primary" 
                link
                @click="handleEdit(scope.row)"
                v-permission="'drug:edit'"
              >
                编辑
              </el-button>
              <el-button 
                type="primary" 
                link
                @click="handleInventory(scope.row)"
                v-permission="'drug:inventory'"
              >
                入库
              </el-button>
              <el-button 
                type="danger" 
                link
                @click="handleDelete(scope.row)"
                v-permission="'drug:delete'"
              >
                删除
              </el-button>
            </el-button-group>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="queryParams.page"
          v-model:page-size="queryParams.limit"
          :page-sizes="[10, 20, 30, 50]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 库存详情对话框 -->
    <el-dialog
      v-model="inventoryDialogVisible"
      title="库存详情"
      width="800px"
    >
      <el-descriptions :column="2" border>
        <el-descriptions-item label="药品名称">{{ currentDrug?.name }}</el-descriptions-item>
        <el-descriptions-item label="药品编码">{{ currentDrug?.drugCode }}</el-descriptions-item>
        <el-descriptions-item label="规格">{{ currentDrug?.specification }}</el-descriptions-item>
        <el-descriptions-item label="生产厂家">{{ currentDrug?.manufacturer }}</el-descriptions-item>
        <el-descriptions-item label="预警数量">{{ currentDrug?.alertQuantity }}</el-descriptions-item>
        <el-descriptions-item label="存储条件">{{ currentDrug?.properties?.storageCondition }}</el-descriptions-item>
      </el-descriptions>

      <el-table
        :data="inventoryList"
        style="width: 100%; margin-top: 20px"
        border
        stripe
      >
        <el-table-column prop="batchNumber" label="批号" width="120" />
        <el-table-column prop="quantity" label="数量" width="100" />
        <el-table-column prop="location" label="库位" min-width="120" />
        <el-table-column prop="expirationDate" label="有效期" width="120" />
        <el-table-column prop="supplier" label="供应商" min-width="150" show-overflow-tooltip />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-tag :type="scope.row.status === '正常' ? 'success' : 'danger'">
              {{ scope.row.status }}
            </el-tag>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { drugAPI } from '@/utils/api'

const router = useRouter()

// 查询参数
const queryParams = reactive({
  page: 1,
  limit: 20,
  name: '',
  drugCode: '',
  category: ''
})

// 数据列表
const drugList = ref([])
const inventoryList = ref([])
const total = ref(0)
const loading = ref(false)

// 当前选中的药品
const currentDrug = ref(null)

// 对话框显示控制
const inventoryDialogVisible = ref(false)

// 获取药品列表
const getDrugList = async () => {
  loading.value = true
  try {
    const res = await drugAPI.getDrugs(queryParams)
    if (res.success) {
      drugList.value = res.data.drugs
      total.value = res.data.total
    } else {
      ElMessage.error('获取药品列表失败')
    }
  } catch (error) {
    console.error('获取药品列表失败', error)
    ElMessage.error('获取药品列表失败')
  } finally {
    loading.value = false
  }
}

// 获取药品库存
const getDrugInventory = async (drugId) => {
  try {
    const res = await drugAPI.getDrugInventory(drugId)
    if (res.success) {
      inventoryList.value = res.data.inventory
    } else {
      ElMessage.error('获取药品库存失败')
    }
  } catch (error) {
    console.error('获取药品库存失败', error)
    ElMessage.error('获取药品库存失败')
  }
}

// 获取药品总库存
const getTotalInventory = (drugId) => {
  return inventoryList.value
    .filter(item => item.drugId === drugId)
    .reduce((total, item) => total + item.quantity, 0)
}

// 获取库存标签类型
const getInventoryTagType = (drugId) => {
  const drug = drugList.value.find(d => d.id === drugId)
  if (!drug) return 'info'
  
  const totalQuantity = getTotalInventory(drugId)
  if (totalQuantity <= 0) return 'danger'
  if (totalQuantity <= drug.alertQuantity) return 'warning'
  return 'success'
}

// 显示库存详情
const showInventoryDetail = async (drug) => {
  currentDrug.value = drug
  await getDrugInventory(drug.id)
  inventoryDialogVisible.value = true
}

// 查询操作
const handleQuery = () => {
  queryParams.page = 1
  getDrugList()
}

// 重置查询
const resetQuery = () => {
  queryParams.name = ''
  queryParams.drugCode = ''
  queryParams.category = ''
  handleQuery()
}

// 分页操作
const handleSizeChange = (val) => {
  queryParams.limit = val
  getDrugList()
}

const handleCurrentChange = (val) => {
  queryParams.page = val
  getDrugList()
}

// 新增药品
const handleAdd = () => {
  console.log('导航到新增药品页面')
  router.push('/drugs/create')
}

// 编辑药品
const handleEdit = (row) => {
  router.push(`/drugs/edit/${row.id}`)
}

// 查看详情
const handleDetail = (row) => {
  router.push(`/drugs/detail/${row.id}`)
}

// 药品入库
const handleInventory = (row) => {
  router.push(`/drugs/inventory/${row.id}`)
}

// 删除药品
const handleDelete = (row) => {
  ElMessageBox.confirm(
    '确认要删除该药品吗？删除后不可恢复',
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      await drugAPI.deleteDrug(row.id)
      ElMessage.success('删除成功')
      getDrugList()
    } catch (error) {
      ElMessage.error('删除失败')
    }
  })
}

// 页面加载时获取数据
onMounted(() => {
  getDrugList()
})
</script>

<style scoped>
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style> 